<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" width="45%">
    <BasicForm @register="registerForm"/>
  </BasicModal>
</template>
<script lang="ts" setup>
  import {ref, computed, unref,reactive} from 'vue';
  import {BasicModal, useModalInner} from '/@/components/Modal';
  import {BasicForm, useForm} from '/@/components/Form';
  import {itemFormSchema} from '../dict.data';
  import {saveOrUpdateDictItem} from '/@/api/infra/dict';
  const emit = defineEmits(['success','register']);
  const props = defineProps({
    dictId: { type: String, default: undefined },
    typeCode: { type: String, default: '' }
  })
  const isUpdate = ref(true);
  const [registerForm, {resetFields, setFieldsValue, validate}] = useForm({
    schemas: itemFormSchema,
    showActionButtonGroup: false,
    mergeDynamicData: props,
    labelWidth: 80,
    wrapperCol: { lg: 24, md: 24 }
  });

  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    await resetFields();
    setModalProps({confirmLoading: false});
    isUpdate.value = !!data?.isUpdate;
    await setFieldsValue({ ...data.record })
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  async function handleSubmit() {
    try {
      const values = await validate();
      values.dictId = props.dictId
      values.dictCode = props.typeCode
      setModalProps({confirmLoading: true});
      await saveOrUpdateDictItem(values, isUpdate.value);
      closeModal();
      emit('success');
    } finally {
      setModalProps({confirmLoading: false});
    }
  }
</script>
